package preorder

import (
    "time"
	"encoding/json"
	"dhfshop/models/consts"
	"dhfshop/utils/helper"
	"dhfshop/controllers/base"
	"dhfshop/models/preorder"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type TimeInsController struct {
	base.BaseController
}

func (this *TimeInsController) PeriodList() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	//partnerId := this.Ctx.Input.GetData("curCompanyId").(int)
	//query["partner_id"] = strconv.Itoa(partnerId)
	l, cnt, err := preorder.GetAllPeriods(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount   int64       `json:"total_count"`
		Period []*preorder.Periods `json:"periods"`
	}{TotalCount: cnt, Period: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *TimeInsController) PeriodUpdate() {
	var v preorder.Periods
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.PeriodsId, "periods_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	if v.ResItemId > 0 {
	    v.ResItem, _= preorder.GetResItemById(v.ResItemId)
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"partner_id,res_item_id,periods_id,timeslots"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(v.SourceAtStr) > 0 {
	    if sourceAt, err := time.Parse(consts.DATE_FORMAT, v.SourceAtStr); err == nil {
			v.SourceAt = sourceAt
		}
	}
	if len(v.TimeSlotJson) > 0 {
	    beego.Debug("v.TimeSlotJson:", v.TimeSlotJson)
		arrJson, err := helper.SplitJsonArr(v.TimeSlotJson)
		if err != nil {
			this.ServeError(err.Error())
		    return
		}
		for _, str := range arrJson {
			var reqTimesSlot preorder.Timeslots
			if err = json.Unmarshal([]byte(str), &reqTimesSlot); err != nil {
				this.ServeError(err.Error())
		        return
			}
			if reqTimesSlot.TimeslotsId < 3 {
			    continue
			}
			reqTimesSlot.Periods = &v               // pay more attention
			if err != nil {
				this.ServeError(err.Error())
				return
			}
			if _, err := preorder.GetTimeslotsById(reqTimesSlot.TimeslotsId); err == nil{
				updateField, err := this.GetUpdateFields(reqTimesSlot, str, "json", []string{""})
				if err != nil {
					this.ServeError(err.Error())
					return
				}
			    if err := preorder.UpdateTimeslotsById(&reqTimesSlot, updateField...); err != nil {
		            this.ServeError(err.Error())
                    return 			
	            }
			}
	    }	
	}
	if len(updateFields) > 0 {
		err := preorder.UpdatePeriodsById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		PeriodsId  int64     `json:"periods_id"`
		Modified  time.Time `json:"modified"`
	}{PeriodsId: v.PeriodsId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *TimeInsController) PeriodDelete() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v := struct {
		PartnerId    int64   `form:"-"  valid:"Required"`
		ResItemId    int64   `form:"res_item_id"`
		PeriodsId    int64   `form:"periods_id"`
		Start        string  `form:"start"`
		End          string  `form:"end"`
	    TimeSlotJson string  `form:"timeslots"`            
	}{PartnerId: partnerId}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	if len(v.TimeSlotJson) > 1 {
	    beego.Debug("v.TimeSlotJson:", v.TimeSlotJson)
		periods := preorder.Periods{}
		err := json.Unmarshal([]byte(v.TimeSlotJson), &periods)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _, timeslot := range periods.Timeslots {
			preorder.DeleteTimeslotsByMultiCond(v.PartnerId,v.PeriodsId,timeslot.TimeslotsId)
		}
	} else {
	    err := preorder.DeletePeriodsByMultiCond(v.PartnerId,v.ResItemId,v.PeriodsId,v.Start,v.End)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		PartnerId int64       `json:"partner_id"`
		Modified  time.Time `json:"modified"`
	}{PartnerId: v.PartnerId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *TimeInsController) PeriodPublic() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	v := struct {
		PartnerId    int64   `form:"-"  valid:"Required"`
		ResItemId    int64   `form:"res_item_id" valid:"Required"`          
	}{PartnerId: partnerId}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	periodIds, err := preorder.GetPeriodsIdByResItemId(v.ResItemId, 0)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	for _, periodId := range periodIds {
	    period := &preorder.Periods{PeriodsId:periodId, Publish:1}
		err := preorder.UpdatePeriodsById(period, "publish")
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		timeslotIds, err := preorder.GetTimeslotIdsByPeriods(partnerId, periodId)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		for _,slotId := range timeslotIds {
			timeslot := &preorder.Timeslots{TimeslotsId:slotId, Publish:1}
			preorder.UpdateTimeslotsById(timeslot, "publish")
		}
	}
	rsp := struct {
		ResItemId int64     `json:"res_item_id"`
		Modified  time.Time `json:"modified"`
	}{ResItemId: v.ResItemId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
